package com.jiang.demo.springbootmultidatasources.dsconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDB1",    //配置连接工厂
        transactionManagerRef = "transactionManagerDB1",    //配置事务管理器
        basePackages = {"com.jiang.demo.springbootmultidatasources.repository.db1"}     //设置 repository 所在位置
)
public class DB1Config {

    //配置数据源
    @Autowired
//    @Qualifier("db2DS")   //默认为db1DS，可以不用指定
    private DataSource db1DS;

    @Primary
    @Bean(name = "entityManagerFactoryDB1")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDB1(EntityManagerFactoryBuilder builder){
        return builder
                .dataSource(db1DS)  //设置数据源
                .packages("com.jiang.demo.springbootmultidatasources.entity.db1")   //设置实体类所在位置，扫描所有带 @Entity 注解的类
                .persistenceUnit("db1PersistenceUnit")
                .build();
    }

    /**
     * 配置事务管理器
     * @param builder
     * @return
     */
    @Bean(name = "transactionManagerDB1")
    PlatformTransactionManager transactionManagerDB1(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactoryDB1(builder).getObject());
    }
}
